package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    //分页显示所有菜品
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page==={},pageSize==={},name===={}",page,pageSize,name);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        Page<Dish> dishPage = new Page<>(page, pageSize);
        dishService.page(dishPage,queryWrapper);

        //先查询出dish的信息，但是dish表里面并没有categoryName
        //可以将获取出dishPage里面的categoryId,然后使用这个Id来查询categoryName
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        //1.先将dishPage使用对象拷贝到dishDtoPage中，但是不拷贝Recodes
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        //2.将Dish的数据复制到DishDto里，并使用获取到的categoryId查询对应的category对象
        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将dish的数据复制进dishDto
            BeanUtils.copyProperties( item,dishDto);

            //根据id获取category对象
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            //将category的Name存放进dishDto
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());

        //将DishDto集合放入分页对象中
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    //新增菜品
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto){
       dishService.addDish(dishDto);
       String key = "CategoryId_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
       redisTemplate.delete(key);
       return R.success("添加成功");
    }

    //根据id显示菜品
    @GetMapping("/{id}")
    public R<DishDto> getDishById(@PathVariable("id") Long id){
        /*DishDto dishDto = new DishDto();
        //根据id获取category对象
        Dish dish = dishService.getById(id);
        Category category = categoryService.getById(dish.getCategoryId());

        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setCategoryName(category.getName());*/
        DishDto dishDto = dishService.getDishById(id);
        return R.success(dishDto);
    }

    @GetMapping("/list")
    //保存数据到redis中

    public R<List<DishDto>> list(Dish dish){
        String key = "CategoryId_"+dish.getCategoryId()+"_"+dish.getStatus();
        List<DishDto> dishDtoList = null;

        //先从redis里面查询菜品信息
       dishDtoList =(List<DishDto>) redisTemplate.opsForValue().get(key);
       if (dishDtoList!=null){
           return R.success(dishDtoList);
       }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);


        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            //将dish基本数据拷贝进行dishDto，然后后面再查询出口味再添加进dishDto
            BeanUtils.copyProperties(item,dishDto);

            //根据id查询分类对象
            Category category = categoryService.getById(item.getCategoryId());

            if(category != null){
                dishDto.setCategoryName( category.getName());
            }

            //根据菜品的id查询出口味
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());

            //将查询出的口味添加进dishDto
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //将查询出来的数据保存进行redis
        System.out.println("保存进行redis");
        redisTemplate.opsForValue().set(key,dishDtoList);

        return R.success(dishDtoList);
    }


   /* //根据菜品类型获取菜品
    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/

    //修改菜品
    @PutMapping
    public R<String> editDish(@RequestBody DishDto dishDto){
        String key = "CategoryId_*";
        dishService.editDish(dishDto);
        //修改菜品后，删除redis中的数据
        //修改菜品必须全部删除，因为你可能修改它的菜品分类，使这个分类的菜品减少，同时使另一个增加，因此必须全部清理
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

   @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){
       String key = "CategoryId_*";
        log.info("ids=={}",ids);
        if (ids.size()>0){
            dishService.removeByIds(ids);
            redisTemplate.delete(key);
            return R.success("删除成功");
        }
        return R.error("删除失败");
   }


}
